package com.itheima.tlias.tliasweb.util;

import com.alibaba.fastjson2.JSONObject;
import com.itheima.tlias.tliasweb.config.QiniuProperties;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.UUID;

/**
 * 参考：
 * https://blog.csdn.net/z583248756/article/details/120867614
 * https://developer.qiniu.com/kodo/1239/java
 * */
@Slf4j
@Component
public class QiniuOssUtil {

    @Autowired
    private QiniuProperties properties;

    public String upload(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        byte[] bytes = file.getBytes();
        return upload(originalFilename, bytes);
    }

    public String upload(String originalFilename, byte[] bytes) throws IOException{
        try {
            int dotPos = originalFilename.lastIndexOf(".");
            if (dotPos < 0) {
                return null;
            }
            String fileExt = originalFilename.substring(dotPos + 1).toLowerCase();
            String fileName = UUID.randomUUID().toString().replaceAll("-", "") + "." + fileExt;
            // 密钥配置
            Auth auth = Auth.create(properties.getAccessKeyId(), properties.getAccessKeySecret());
            // 构造一个带指定Zone对象的配置类,不同的七云牛存储区域调用不同的zone
            Configuration cfg = new Configuration(Zone.zone1());
            // ...其他参数参考类注释
            UploadManager uploadManager = new UploadManager(cfg);
            // 获取上传的token， 简单上传，使用默认策略，只需要设置上传的空间名就可以了
            String token = auth.uploadToken(properties.getBucketName());
            // 调用put方法上传
            Response res = uploadManager.put(bytes, fileName, token);
            // 打印返回的信息
            if (res.isOK() && res.isJson()) {
                // 如果bucket是私有访问权限
                if(properties.isAccessPrivate()){
                    // 生成下载地址
                    String encodedFileName = URLEncoder.encode(fileName, "utf-8").replace("+", "%20");
                    String publicUrl = String.format("%s/%s", properties.getEndpoint(), encodedFileName);
                    return auth.privateDownloadUrl(publicUrl, 3600);
                }else{
                    // 拼接返回地址
                    return UrlUtil.join(properties.getEndpoint(), JSONObject.parseObject(res.bodyString()).getString("key"));
                }
            } else {
                log.error("七牛异常:" + res.bodyString());
                return null;
            }
        } catch (QiniuException e) {
            // 请求失败时打印的异常的信息
            log.error("七牛异常:" + e.getMessage());
            return null;
        }
    }

    public String downloadPrivate(String filename, int expireSeconds) throws Exception{
        String encodedFileName = URLEncoder.encode(filename, "utf-8").replace("+", "%20");
        String publicUrl = String.format("%s/%s", properties.getEndpoint(), encodedFileName);
        Auth auth = Auth.create(properties.getAccessKeyId(), properties.getAccessKeySecret());
        String finalUrl = auth.privateDownloadUrl(publicUrl, expireSeconds);
        return finalUrl;
    }

    public String parseFileNameFromUrl(String url){
        int protocol = url.indexOf("://");
        int slash = url.indexOf("/", protocol + 4);
        int ask = url.indexOf("?");
        return url.substring(slash+1, ask);
    }

}